package com.dongdong.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.dongdong.utils.PayUtils;
import com.dongdong.utils.Result;
import com.dongdong.utils.ResultEnum;
import com.dongdong.vo.RefundQueryVO;
import com.dongdong.vo.RefundVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private PayUtils payUtils;

    @Autowired
    private AlipayClient alipayClient;

    /**
     * 支付
     * @param outTradeNo
     * @param totalAmount
     * @param subject
     * @return
     */
    @GetMapping("/aliPay")
    public String aliPay(@RequestParam String outTradeNo, @RequestParam String totalAmount, @RequestParam String subject) {

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(payUtils.getNotifyUrl());
//同步跳转地址，仅支持http/https
        request.setReturnUrl(payUtils.getReturnUrl());
        /*必传参数*/
        JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
        bizContent.put(payUtils.getOutTradeNo(), outTradeNo);
//支付金额，最小值0.01元
        bizContent.put(payUtils.getTotalAmount(), totalAmount);
//订单标题，不可使用特殊符号
        bizContent.put(payUtils.getSubject(), subject);
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put(payUtils.getProductCode(), payUtils.getProduct());


        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return response.getBody();
    }

    /**
     * 根据流水号查询订单
     * @param tradeNo
     * @return
     */
    @GetMapping("/tradeQuery")
    public Result tradeQuery(@RequestParam String tradeNo){
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("trade_no",tradeNo);
        request.setBizContent(JSONObject.toJSONString(jsonObject));
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            return Result.OK().setData(response.getBody());
        } else {
            System.out.println("调用失败");
            return Result.FAIL();
        }
    }

    /**
     * 退款
     * @param tradeNo 流水号
     * @param refundAmount 退款金额
     * @param outRequestNo 退款请求号
     * @return
     */
    @GetMapping("/refund")
    public Result refund(@RequestParam String tradeNo,@RequestParam String refundAmount,@RequestParam String outRequestNo){
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("refund_amount", refundAmount);
        bizContent.put("out_request_no", outRequestNo);


        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
//            是否退款成功
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            Object refundResponse = jsonObject.get("alipay_trade_refund_response");
            String s = JSONObject.toJSONString(refundResponse);
            RefundVO refundVO = JSONObject.parseObject(s, RefundVO.class);
//判断
            if (!Objects.equals(refundVO.getFundChange(),"Y")){
//                进一步查询
                RefundQueryVO refundQueryVO = refundQuery(tradeNo, outRequestNo);
                if (!Objects.equals(refundQueryVO.getRefundStatus(),"REFUND_SUCCESS")){
                    return Result.DATA(ResultEnum.REFUND_FAIL);
                }else {
                    return Result.DATA(ResultEnum.REFUND_REPEAT);
                }
            }else {
                return Result.DATA(ResultEnum.REFUND_SUCCESS);
            }

        } else {
            System.out.println("调用失败");
        }
        return null;
    }

    /**
     * 交易退款查询
     * @param tradeNo 流水号
     * @param outRequestNo 退款请求号
     */
    public RefundQueryVO refundQuery( String tradeNo, String outRequestNo){

        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("out_request_no", outRequestNo);


        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            Object refundQuery = jsonObject.get("alipay_trade_fastpay_refund_query_response");
            String s = JSONObject.toJSONString(refundQuery);
            RefundQueryVO refundQueryVO = JSONObject.parseObject(s, RefundQueryVO.class);

            return refundQueryVO;
        } else {
            System.out.println("调用失败");
            return null;
        }
    }
}
